import React, { Children, Fragment, useEffect, useState } from 'react';
import { Form, Input, Space, Row, Col, DatePicker, Divider, Modal, Button } from 'antd';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useTRState, useStaticState } from '#/utils/trHooks';
import {
  CREATE_LINKED_FORM_ITEM_LIST,
  VIEW_LINKED_FORM_ITEM_LIST,
  LINKED_FORM_ITEM_LIST,
  COMPANY_TABLE_COLUMNS_LIST,
  MODULE_TABLE_COLUMNS_LIST,
  INSTANCE_VIEW_LINKED_FORM_ITEM_LIST,
  TASK_LOG_LIST,
} from './helper';
import { companyList, grabModuleList } from './service';
// import { TRCheckboxModal } from '@/components/index.js';
import TRCheckboxModal from '../../SchemaRender/TRCheckboxModal';
import { TRTable } from '../../SchemaRender';
import CreateCron from './createCron';
import moment from 'moment';
import styles from './index.less';

const DRFormItem = (props) => {
  const {
    form: propsForm,
    isVertical,
    formType = 'create',
    topSearchForm,
    editRecord,
    viewRecord,
    handleReset,
  } = props;

  // const isEmpty = !treeData.length;
  const [state, setState] = useTRState({
    linkedOptions: {
      retryTypeList: [],
    },
  });

  const staticState = useStaticState({
    LINKED_FORM_ITEM_LIST: {
      create: CREATE_LINKED_FORM_ITEM_LIST,
      view: VIEW_LINKED_FORM_ITEM_LIST,
      instanceView: INSTANCE_VIEW_LINKED_FORM_ITEM_LIST,
      edit: LINKED_FORM_ITEM_LIST,
    },
  });

  const [companyTableDataSource, setCompanyTableDataSource] = useState([]);
  const [moduleTableDataSource, setModuleTableDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [status, setStatus] = useState('');
  const [companyListData, setCompanyListData] = useState([]);
  const [grabModuleListData, setGrabModuleListData] = useState([]);
  const [companyListCheckedKeys, setCompanyListCheckedKeys] = useState([]);
  const [grabModuleListCheckedKeys, setGrabModuleListCheckedKeys] = useState([]);
  const [reDisable, setReDisable] = useState(false);
  const [taskLog, setTaskLog] = useState([]);
  const [logViewDrawerVisible, setLogViewDrawerVisible] = useState(false);
  const [logViewDrawerContent, setLogViewDrawerContent] = useState('');
  const ItemLineContainer = isVertical ? Row : Fragment;
  const ItemLineContainerProps = isVertical ? { gutter: 16 } : {};
  const ItemLineCol = isVertical ? Col : Fragment;
  const itemLineColProps = isVertical ? { span: 8 } : {};

  useEffect(() => {
    initFormData();
  }, [viewRecord, editRecord]);

  useEffect(() => {
    if (handleReset === true) {
      setCompanyTableDataSource([]);
      setModuleTableDataSource([]);
    }
  }, [handleReset]);

  // 点击弹出Modal框
  const handelSelectDealElement = async (event) => {
    const selectInfo = event.target.innerText;
    const result = await TRCheckboxModal.show({
      treeData: selectInfo === '选择公司' ? companyListData : grabModuleListData,
      value: selectInfo === '选择公司' ? companyListCheckedKeys : grabModuleListCheckedKeys,
      title: selectInfo,
    });

    if (selectInfo === '选择公司') {
      if (result?.index === 1 && result.checkedKeys.length) {
        const newCheckedNodes = result.checkedNodes.map(({ key, title }, index) => ({
          id: index + 1,
          companyCode: key,
          companyName: title,
        }));
        setCompanyTableDataSource(newCheckedNodes);
        propsForm.setFieldsValue({ companyList: newCheckedNodes });
      }
    } else {
      if (result?.index === 1 && result.checkedKeys.length) {
        const newCheckedNodes = result.checkedNodes.map(({ key, title }, index) => ({
          id: index + 1,
          grabModuleCode: key,
          grabModuleName: title,
        }));
        setModuleTableDataSource(newCheckedNodes);
        propsForm.setFieldsValue({ grabModuleList: newCheckedNodes });
      }
    }

    TRCheckboxModal.dismiss();
  };

  const replaceEmptyStrings = (obj) => {
    if (Array.isArray(obj)) {
      return obj.map((item) => replaceEmptyStrings(item));
    } else if (obj && typeof obj === 'object') {
      return Object.fromEntries(
        Object.entries(obj).map(([key, value]) => {
          if (value === '' || value === null) {
            return [key, '--'];
          } else if (typeof value === 'object' && value !== null) {
            return [key, replaceEmptyStrings(value)];
          } else {
            return [key, value];
          }
        }),
      );
    }
    return obj;
  };

  const initFormData = async () => {
    if (viewRecord) {
      viewRecord.retry = (await viewRecord.retry) === false ? '否' : '是';

      viewRecord.valid = (await viewRecord.valid) === 1 ? '启用' : '禁用';

      switch (viewRecord.priority) {
        case 'HIGHEST':
          viewRecord.priority = '最高级';
          break;
        case 'HIGH':
          viewRecord.priority = '高级';
          break;
        case 'MEDIUM':
          viewRecord.priority = '中级';
          break;
        case 'LOW':
          viewRecord.priority = '低级';
          break;
        case 'LOWEST':
          viewRecord.priority = '最低级';
          break;
        default:
          break;
      }

      if (viewRecord.taskInstanceLogData) {
        setTaskLog(await viewRecord.taskInstanceLogData);
      } else {
        setTaskLog([]);
      }

      const updatedTask = replaceEmptyStrings(viewRecord);

      propsForm.setFieldsValue(updatedTask);

      // 关联流程默认数据测试
      propsForm.setFieldsValue({
        process: [
          {
            processId: '1',
            processName: '流程1',
            createTime: viewRecord.createAt,
            createUser: '用户1',
          },
          {
            processId: '2',
            processName: '流程2',
            createTime: viewRecord.createAt,
            createUser: '用户2',
          },
        ],
      });

      setCompanyTableDataSource([...updatedTask.companyList]);

      setModuleTableDataSource([...updatedTask.grabModuleList]);

      // 关联流程默认数据测试
      propsForm.setFieldsValue({
        process: [
          {
            processId: '1',
            processName: '流程1',
            createTime: moment().format('YYYY-MM-DD'),
            createUser: '用户1',
          },
          {
            processId: '2',
            processName: '流程2',
            createTime: moment().format('YYYY-MM-DD'),
            createUser: '用户2',
          },
        ],
      });
    }

    if (editRecord) {
      propsForm.setFieldsValue(editRecord);

      setCompanyListCheckedKeys([...editRecord.companyList.map((item) => item.companyCode)]);

      setGrabModuleListCheckedKeys([
        ...editRecord.grabModuleList.map((item) => item.grabModuleCode),
      ]);

      setCompanyTableDataSource([...editRecord.companyList]);

      setModuleTableDataSource([...editRecord.grabModuleList]);

      // 关联流程默认数据测试
      propsForm.setFieldsValue({
        process: [
          {
            processId: '1',
            processName: '流程1',
            createTime: moment(),
            createUser: '用户1',
          },
          {
            processId: '2',
            processName: '流程2',
            createTime: moment(),
            createUser: '用户2',
          },
        ],
      });
    }

    await companyList().then((res) => {
      if (res.statusCode === '1000') {
        setCompanyListData([...res?.data]);
      }
    });

    await grabModuleList().then((res) => {
      if (res.statusCode === '1000') {
        setGrabModuleListData([...res?.data]);
      }
    });
  };

  const handleFormItemValueChange = (formItemValue, listItem) => {
    if (listItem?.key === 'retry') {
      if (!formItemValue) {
        setReDisable(true);
      } else {
        setReDisable(false);
      }
    }
  };

  // 根据数据源是否有数据来决定表格的高度
  const getHeight = (listItem) => {
    if (listItem.key === 'companyList') {
      return companyTableDataSource?.length > 0 ? 'auto' : '100px';
    } else {
      return moduleTableDataSource?.length > 0 ? 'auto' : '100px';
    }
  };

  const onCreate = (values) => {
    propsForm.setFieldsValue({ cronTime: values });
    setVisible(false);
  };

  const openCron = (bool, stats) => {
    setVisible(bool);
    setStatus(stats);
  };

  const showLogViewDrawer = async (value) => {
    setLogViewDrawerVisible(true);
    setLogViewDrawerContent(value);
  };

  return (
    <>
      {staticState.LINKED_FORM_ITEM_LIST[formType].map((linkedFormItem) => {
        return (
          <>
            <p
              style={{
                marginBottom: '24px',
                fontWeight: '500',
                fontSize: '18px',
                lineHeight: '18px',
                textAlign: 'left',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              {linkedFormItem.infoTitle}
              {linkedFormItem.selectInfo && formType !== 'view' ? (
                <div
                  style={{
                    marginLeft: '20px',
                    width: '80px',
                    height: '36px',
                    borderRadius: '8px',
                    color: 'var(--font-primary)',
                    fontSize: '16px',
                    border: '1px solid var(--bd)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontWeight: '500',
                    cursor: 'pointer',
                  }}
                  onClick={handelSelectDealElement}
                >
                  {linkedFormItem.selectInfo}
                </div>
              ) : null}
            </p>
            <ItemLineContainer key={linkedFormItem.infoTitle} {...ItemLineContainerProps}>
              {linkedFormItem.list.map((listItem) => {
                return linkedFormItem.selectInfo ? (
                  <ItemLineCol key={listItem.key} span={listItem.span}>
                    <Form.Item key={listItem.key} name={listItem.key}>
                      <TRTable
                        columns={
                          listItem.key === 'companyList'
                            ? COMPANY_TABLE_COLUMNS_LIST()
                            : MODULE_TABLE_COLUMNS_LIST()
                        }
                        style={{
                          width: '1064px',
                          height: getHeight(listItem), // 动态设置高度
                        }}
                        tableData={
                          listItem.key === 'companyList'
                            ? companyTableDataSource
                            : moduleTableDataSource
                        }
                      />
                    </Form.Item>
                  </ItemLineCol>
                ) : linkedFormItem.process && formType !== 'view' ? (
                  <ItemLineCol key={listItem.key} span={listItem.span}>
                    <Form.List name="process">
                      {(fields, { add, remove }) => {
                        return (
                          <>
                            {fields.map(({ key, name, ...restField }) => (
                              <Space
                                key={key}
                                style={{
                                  display: 'flex',
                                  marginBottom: 8,
                                  alignItems: 'center',
                                }}
                                align="baseline"
                              >
                                <Row gutter={16} style={{ width: '1053px' }}>
                                  <Col span={2}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'processId']}
                                      label="序号"
                                    >
                                      <Input />
                                    </Form.Item>
                                  </Col>
                                  <Col span={9}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'processName']}
                                      rules={[
                                        {
                                          required: true,
                                          message: '请输入流程名称',
                                        },
                                      ]}
                                      label="流程名称"
                                    >
                                      <Input placeholder="请输入" allowClear />
                                    </Form.Item>
                                  </Col>
                                  <Col span={7}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'createTime']}
                                      rules={[
                                        {
                                          required: true,
                                          message: '请选择创建时间',
                                        },
                                      ]}
                                      label="创建时间"
                                    >
                                      <DatePicker
                                        style={{ width: '290px' }}
                                        placeholder="请选择"
                                        allowClear
                                      />
                                    </Form.Item>
                                  </Col>
                                  <Col span={6}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'createUser']}
                                      rules={[
                                        {
                                          required: true,
                                          message: '请输入创建人',
                                        },
                                      ]}
                                      label="创建人"
                                    >
                                      <Input placeholder="请输入" allowClear />
                                    </Form.Item>
                                  </Col>
                                </Row>
                                <MinusCircleOutlined onClick={() => remove(name)} />
                              </Space>
                            ))}
                            <Form.Item>
                              <div
                                style={{ color: '#1E7CE8', cursor: 'pointer', width: '90px' }}
                                onClick={() => add()}
                              >
                                <PlusCircleOutlined style={{ marginRight: '8px' }} />
                                继续添加
                              </div>
                            </Form.Item>
                          </>
                        );
                      }}
                    </Form.List>
                  </ItemLineCol>
                ) : linkedFormItem.process && formType === 'view' ? (
                  <ItemLineCol key={listItem.key} span={listItem.span}>
                    <Form.List name="process">
                      {(fields) => {
                        return (
                          <>
                            {fields.map(({ key, name, ...restField }) => (
                              <Space
                                key={key}
                                style={{
                                  display: 'flex',
                                  marginBottom: 8,
                                  alignItems: 'center',
                                }}
                                align="baseline"
                              >
                                <Row gutter={16} style={{ width: '1053px' }}>
                                  <Col span={2}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'processId']}
                                      label="序号"
                                    >
                                      <Input {...listItem.attrs} />
                                    </Form.Item>
                                  </Col>
                                  <Col span={9}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'processName']}
                                      label="流程名称"
                                    >
                                      <Input {...listItem.attrs} />
                                    </Form.Item>
                                  </Col>
                                  <Col span={7}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'createTime']}
                                      label="创建时间"
                                    >
                                      {/* <DatePicker {...listItem.attrs} format="YYYY-MM-DD" /> */}
                                      <Input {...listItem.attrs} />
                                    </Form.Item>
                                  </Col>
                                  <Col span={6}>
                                    <Form.Item
                                      {...restField}
                                      name={[name, 'createUser']}
                                      label="创建人"
                                    >
                                      <Input {...listItem.attrs} />
                                    </Form.Item>
                                  </Col>
                                </Row>
                              </Space>
                            ))}
                          </>
                        );
                      }}
                    </Form.List>
                  </ItemLineCol>
                ) : linkedFormItem.taskLog && formType === 'instanceView' ? (
                  <ItemLineCol key={listItem.key} span={listItem.span}>
                    <Form.Item key={listItem.key} name={listItem.key}>
                      <TRTable
                        columns={TASK_LOG_LIST({
                          showLogViewDrawer,
                        })}
                        style={{
                          width: '1064px',
                          height: taskLog?.length > 0 ? 'auto' : '100px',
                        }}
                        tableData={taskLog}
                        // hasPagination
                        paginationConfig={{
                          current: 1,
                          pageSize: 20,
                          total: taskLog.length,
                        }}
                      />
                    </Form.Item>
                  </ItemLineCol>
                ) : listItem.key === 'executeScript' ? (
                  <ItemLineCol key={listItem.key} span={listItem.span}>
                    <Form.Item
                      key={listItem.key}
                      name={listItem.key}
                      label={listItem.label}
                      rules={listItem.rules}
                      shouldUpdate
                    >
                      <listItem.components
                        {...listItem.attrs}
                        style={{
                          width: listItem?.width,
                          minWidth: listItem?.minWidth,
                          minHeight: listItem?.minHeight,
                          height: listItem?.height,
                          padding: listItem?.padding,
                          marginLeft: `${isVertical ? 0 : 12}px`,
                        }}
                        options={
                          listItem?.options || state.linkedOptions[listItem?.optionsKey] || []
                        }
                        onChange={(formItemValue) =>
                          handleFormItemValueChange(formItemValue, listItem)
                        }
                      />
                    </Form.Item>
                  </ItemLineCol>
                ) : (
                  <ItemLineCol key={listItem.key} {...itemLineColProps}>
                    <Form.Item
                      key={listItem.key}
                      name={listItem.key}
                      label={listItem.label}
                      rules={listItem.rules}
                      shouldUpdate
                    >
                      {listItem.key === 'cronTime' && formType !== 'view' ? (
                        <listItem.components
                          {...listItem.attrs}
                          style={{
                            width: listItem?.width,
                            height: listItem?.height,
                            marginLeft: `${isVertical ? 0 : 12}px`,
                          }}
                          onClick={() => {
                            openCron(true, '新建');
                          }}
                        />
                      ) : (
                        <listItem.components
                          {...listItem.attrs}
                          style={{
                            width: listItem?.width,
                            minWidth: listItem?.minWidth,
                            minHeight: listItem?.minHeight,
                            height: listItem?.height,
                            padding: listItem?.padding,
                            marginLeft: `${isVertical ? 0 : 12}px`,
                          }}
                          options={
                            listItem?.options || state.linkedOptions[listItem?.optionsKey] || []
                          }
                          showSearch={listItem.key === 'tradingCenterCode'}
                          filterOption={(input, option) => {
                            return (option?.label).toLowerCase().includes(input.toLowerCase());
                          }}
                          onChange={(formItemValue) =>
                            handleFormItemValueChange(formItemValue, listItem)
                          }
                        />
                      )}
                    </Form.Item>
                  </ItemLineCol>
                );
              })}
            </ItemLineContainer>
            <Divider />
            <CreateCron
              visible={visible}
              status={status}
              onCreate={onCreate}
              onCancel={() => {
                setVisible(false);
              }}
            />
            <Modal
              width={720}
              className={styles.modal}
              centered={true}
              visible={logViewDrawerVisible}
              onOk={() => {
                setLogViewDrawerVisible(false);
              }}
              onCancel={() => {
                setLogViewDrawerVisible(false);
              }}
              maskClosable={true}
              title={
                <div key="title" className={styles.modal_title}>
                  实例日志内容查看
                </div>
              }
            >
              <pre style={{ width: '100%', height: '320px', whiteSpace: 'pre-wrap' }}>
                {logViewDrawerContent}
              </pre>
            </Modal>
          </>
        );
      })}
    </>
  );
};

export default DRFormItem;
